package com.example.demo1.exception;

import com.example.demo1.common.AppResult;
import com.example.demo1.common.ResultCode;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolationException;

import java.net.BindException;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ApplicationException.class)
    public AppResult<Void> handleApplicationException(ApplicationException e) {
        return AppResult.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler({
            MethodArgumentNotValidException.class,
            BindException.class,
            ConstraintViolationException.class,
            IllegalArgumentException.class
    })
    public AppResult<Void> handleValidationException(Exception e) {
        return AppResult.error(ResultCode.BAD_REQUEST.getCode(),
                "参数验证失败: " + e.getMessage());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public AppResult<Void> handleJsonParseException() {
        return AppResult.error(ResultCode.BAD_REQUEST.getCode(),
                "JSON解析失败，请检查请求体格式");
    }

    @ExceptionHandler(Exception.class)
    public AppResult<Void> handleException(Exception e) {
        e.printStackTrace();
        return AppResult.error(ResultCode.INTERNAL_ERROR);
    }
}
